mod model;
mod controller;
mod util;
mod config;

use actix_web::{HttpServer, App, web::Data, cookie::Key};
use actix_session::{SessionMiddleware, storage::CookieSessionStore};
use sea_orm::DatabaseConnection;

#[derive(Clone)]
pub struct AppState {
    db: DatabaseConnection
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let config = config::Config::from_env();

    let state = AppState {
        db: model::init_db(&config.mysql_url).await.unwrap()
    };

    HttpServer::new(move || {
        App::new()
            .wrap(
                SessionMiddleware::builder(
                    CookieSessionStore::default(),
                    Key::from(&config.session_key)
                ).cookie_secure(false).build()
            )
            .app_data(Data::new(state.clone()))
            .service(controller::user::login)
            .service(controller::user::logout)
            .service(controller::user::get_login_status)
            .service(controller::user::change_password)
            .service(controller::user::create_user)
            .service(controller::user::get_user_list)
            .service(controller::post::create_post)
            .service(controller::post::delete_post)
            .service(controller::post::update_post)
            .service(controller::post::get_post_list)
    }).bind(&config.bind_addr)?.run().await
}
